import Vue from 'vue'
import VueRouter from 'vue-router'
import Manager from '../views/Manager'
import Login from "@/views/Login";
import Register from "@/views/Register";
import Auth from "@/views/manager/Auth";


Vue.use(VueRouter)

//解决点击重复路由时报错问题
//Avoided redundant navigation to current location: "/user".
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    name: 'Manager',
    component: Manager,
    redirect:'/home',
    children:[
        //无权限里跳转的页面
      {path: '403', name: 'Auth',meta:{name:'没有权限访问'}, component: Auth},
      {path:'home',name:'Home',meta:{name:'系统主页'},component:()=>import('@/views/manager/Home')},
      {path:'user',name:'user',meta:{name:'用户信息'},component:()=>import('@/views/manager/User')},
      {path:'news',name:'news',meta:{name:'新闻信息'},component:()=>import('@/views/manager/News')},
      {path:'person',name:'Person',meta:{name:'个人信息'},component:()=>import('@/views/manager/Person')},
      {path:'password',name:'Password',meta:{name:'修改密码'},component:()=>import('@/views/manager/Password')},
      {path:'notice',name:'Notice',meta:{name:'系统公告'},component:()=>import('@/views/manager/Notice')},
      {path:'logs',name:'Logs',meta:{name:'系统公告'},component:()=>import('@/views/manager/Logs')},
      {path:'orders',name:'Orders',meta:{name:'订单信息'},component:()=>import('@/views/manager/Orders')},
      {path:'charts',name:'Charts',meta:{name:'数据统计'},component:()=>import('@/views/manager/Charts')}
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '*',
    name: '404',
    component: ()=>import('@/views/404')
  },

]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

//Vue的路由守卫
router.beforeEach((to,from,next)=>{
  console.log(to.path)
  /**
   * to :到达的路由信息
   * from : 来源的路由信息
   * next :跳转路由的函数
   */

  const adminPath = ['/user']
  const user = JSON.parse(localStorage.getItem("user") || '{}')
  console.log(user)
  if (user.role !== '管理员' && adminPath.includes(to.path)){
    next('/403')  //如果访问到没有权限的路径参数，则跳转至403页面
  }else {
    next()  //放行
  }

})

export default router
